var Q = require("q");
var entityCollection = require('../../../Base/server/controllers/EntityCollection');

exports.queryBizCount = function(req, res) {
    queryRecordCount(req, res).then(findItemMasterByBarcode).catch(function(err) {
        res.json({
            Error: err
        });
    }).done();
};

function queryRecordCount(req, res) {
    var deferred = Q.defer();
    var entityItem = entityCollection.getEntity("BizRecord");
    var entityTerminal = entityCollection.getEntity("Terminal");
    entityTerminal.find({
        UniqueID: req.body.uniqueID
    }, null, null, function(error, record) {
        if (!error && record) {
            entityItem.queryRecordCount({
                CollectDateTime: {
                    "$gte": req.body.time
                },
                Terminal: record[0]._id
            }, function(err, r) {
                if (!err) {
                    var result = {};
                    result['count'] = r;
                    result['barcode'] = req.body.barcode
                    result['res'] = res;
                    deferred.resolve(result);
                } else {
                    deferred.reject(err);
                }
            })
        }
    });

    return deferred.promise;
};

function findItemMasterByBarcode(req, res) {
    var deferred = Q.defer();
    var entityItem = entityCollection.getEntity("BarcodeMaster");
    entityItem.find({
        Barcode: req.barcode
    }, null, null, function(err, record) {
        if (!err) {
            var result = {};
            result['count'] = req.count;
            result['itemcode'] = '未找到对应料品';
            if (record && record[0].ItemMasterCode) {
                result['itemcode'] = record[0].ItemMasterCode;
            };
            req.res.json(result);
            deferred.resolve(result);
        }
    });
    return deferred.promise;
}